﻿#include "contact.h"
#include "ui_contact.h"
#include"contactitem.h"
#include<QSqlQueryModel>
#include<QSqlQuery>
#include<QFile>
#include<QMessageBox>
#include<QPainter>
#include"msgwebview.h"
#include<QTextStream>
extern int gAccount;
int ReceiverAccount;//接受者账号
contact::contact(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::contact)
{
    ui->setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint);
    loadStyleSheet();
    initControl();
    QStringList userList;
    getUserList(userList);
    if(!createJSFile(userList)){
        QMessageBox::critical(this, QString::fromLocal8Bit("error"), QString::fromLocal8Bit("write js file fail!"));
    }
}

contact::~contact()
{
    delete ui;
}

void contact::initControl()
{
    QSqlQueryModel model;
    QString str=QString("select username,picture,account from info where account!=%1").arg(gAccount);
    model.setQuery(str);
    QPixmap mask;
    mask.load(":/src/img/head_mask.png");
    for(int i=0;i<model.rowCount();i++){
        QModelIndex nameIndex=model.index(i,0);
        QModelIndex picIndex=model.index(i,1);
        QModelIndex accountIndex=model.index(i,2);
        QString name=model.data(nameIndex).toString();
        QString picture=model.data(picIndex).toString();
        int account=model.data(accountIndex).toInt();
        contactItem*item=new contactItem(ui->listWidget);
        QListWidgetItem*listItem=new QListWidgetItem(ui->listWidget);
        listItem->setData(Qt::UserRole,account);
        listItem->setSizeHint(QSize(280,60));
        item->setUsername(name);
        item->setHeadPicture(getRoundImg(QPixmap(picture),mask,item->getHeadSize()));
        ui->listWidget->addItem(listItem);
        ui->listWidget->setItemWidget(listItem,item);
    }
    connect(ui->listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem *)),
            this,SLOT(onItemDoubleClicked(QListWidgetItem*)));
}

void contact::loadStyleSheet()
{
    QFile file(":/src/QSS/contact.css");
    if(file.open(QFile::ReadOnly)){
        QString str=file.readAll();
        setStyleSheet(str);
        file.close();
    }else{
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("加载样式表失败!"));
    }
}

QPixmap contact::getRoundImg(const QPixmap &src, QPixmap &mask, QSize maskSize)
{
    if (maskSize == QSize(0, 0)) {
            maskSize = mask.size();
        }
        else {
            mask = mask.scaled(maskSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }
        QImage resultImage(maskSize, QImage::Format_ARGB32_Premultiplied);
        QPainter painter(&resultImage);
        painter.setCompositionMode(QPainter::CompositionMode_Source);
        painter.fillRect(resultImage.rect(), Qt::transparent);
        painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
        painter.drawPixmap(0, 0, mask);
        painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        painter.drawPixmap(0, 0, src.scaled(maskSize,Qt::KeepAspectRatio, Qt::SmoothTransformation));
        painter.end();
        return QPixmap::fromImage(resultImage);
}

void contact::getUserList(QStringList &userList)
{
    QSqlQueryModel model;
    QString str="select account from info";
    model.setQuery(str);
    int count=model.rowCount();
    for(int i=0;i<count;i++){
        QModelIndex index=model.index(i,0);
        userList<<model.data(index).toString();
    }
}

bool contact::createJSFile(QStringList &userList)
{
    QFile file("src/msgtmpl.txt");
        QString str;
        if (file.open(QFile::ReadOnly)) {
            str = file.readAll();
            file.close();
        }
        else {
            QMessageBox::critical(this, "error", "open msgtmpl.txt fail");
            return false;
        }
        QFile js("src/msgtmpl.js");
        if (js.open(QFile::WriteOnly | QFile::Truncate)) {
            QString initNull = "var external = null;";
            QString initObj = "external = channel.objects.external;";
            QString initRecv;
            //QString中不支持出现双引号,即时用转义字符也没有效果,所以这里采用文件的方式
            QFile recvFile("src/recvHtml.txt");
            if (recvFile.open(QIODevice::ReadOnly)) {
                initRecv = recvFile.readAll();
                recvFile.close();
            }
            else {
                QMessageBox::critical(this, "error", "open recvHtml.txt fail");
                return false;
            }

            QString replaceNull;
            QString replaceObj;
            QString replaceRecv;
            for (int i = 0; i < userList.length(); i++) {
                QString strNull = initNull;
                strNull.replace("external", QString("external_%1").arg(userList[i]));
                replaceNull += strNull;
                replaceNull += "\n";

                QString strObj = initObj;
                strObj.replace("external", QString("external_%1").arg(userList[i]));
                replaceObj += strObj;
                replaceObj += "\n";

                QString strRecv = initRecv;
                strRecv.replace("external", QString("external_%1").arg(userList[i]));
                strRecv.replace("recvHtml", QString("recvHtml_%1").arg(userList[i]));
                replaceRecv += strRecv;
                replaceRecv += "\n";
        }
            str.replace(initNull, replaceNull);
            str.replace(initObj, replaceObj);
            str.replace(initRecv, replaceRecv);
            QTextStream stream(&js);
            stream << str;
            js.close();
            return true;
        }
        else {
            QMessageBox::critical(this, "error", "write msgtmpl.js fail");
            return false;
        }
}

void contact::onItemDoubleClicked(QListWidgetItem *item)
{
    ReceiverAccount=item->data(Qt::UserRole).toInt();
    msgWebView*view=new msgWebView(item->data(Qt::UserRole).toInt());
    connect(view,&msgWebView::deleteSrc,[view]{
        delete view;//及时释放,防止内存泄漏
    });
    view->show();
}

void contact::on_closeBtn_clicked()
{
    close();
}

void contact::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton){
        m_point=event->globalPos()-mapToGlobal(QPoint(0,0));
        event->accept();
    }
}

void contact::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton){
        move(event->globalPos()-m_point);
        event->accept();
    }
}
